package com.platform.cdcs.fragment.custom;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.R;
import com.platform.cdcs.fragment.choose.AccountChooseFragment;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.DisProductList;
import com.platform.cdcs.model.MockObj;
import com.platform.cdcs.model.PriceItem;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.FragmentUtil;
import com.platform.cdcs.tool.ViewTool;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.tool.Utils;
import com.trueway.app.uilib.widget.TwDialogBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Call;

/**
 * Created by holytang on 2017/11/20.
 */
public class CustomDetailFragment extends BaseFragment {

    private View rootView;
    private DisProductList.DisProduct item;
    private EditText custNameET, custCodeET, codeET;
    private TextView lineNameET, unitET, accountET, nameET;
    private EditText addressET, typeET, numberET, code1ET, unit1ET, markET;
    private String[] unitArray;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        item = (DisProductList.DisProduct) getArguments().getSerializable("model");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void initView(View view) {
        initLoadImg(view.findViewById(R.id.load));
        setTitle("详情");
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        rootView = view;
        rootView.findViewById(R.id.text).setVisibility(View.GONE);
        requestDetail();
    }

    @Override
    public int layoutId() {
        return R.layout.five_layout;
    }

    private void requestDetail() {
        showLoadImg();
        Map<String, String> param = new HashMap<>();
        param.put("id", item.getId());
        getHttpClient().post().url(Constant.DIST_PRODUCT_INFO).params(Constant.makeParam(param)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getActivity(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    if (getContext() == null) {
                        return;
                    }
                    dismissLoadImg();
                    Type type = new TypeToken<DisProductList>() {
                    }.getType();
                    DisProductList response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getCode())) {
                        setData(response.getDistProductInfo());
                    } else {
                        Utils.showToast(getContext(), response.getMsg());
                    }
                } catch (Exception e) {
                    Utils.showToast(getContext(), "解析失败!");
                }
            }
        });
    }

    private void setData(final DisProductList.DisProduct data) {
        TextView btn1 = (TextView) rootView.findViewById(R.id.text);
        btn1.setVisibility(View.VISIBLE);
        btn1.setText("修改");
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editPost();
            }
        });
        TextView btn2 = (TextView) rootView.findViewById(R.id.text1);
        btn2.setBackgroundResource(R.drawable.btn_red);
        btn2.setText("删除");
        btn2.setVisibility(View.VISIBLE);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deletePost();
            }
        });


        LayoutInflater inflater = LayoutInflater.from(getContext());
        LinearLayout root1 = (LinearLayout) rootView.findViewById(R.id.button1);
        EditText[] editTexts = ViewTool.setFourItemEdit(inflater, root1, new String[]{"自定义产品代码", "产品标准代码"}, new String[]{data.getMaterialNumber(), data.getMaterialStCode()});
        custCodeET = editTexts[0];
        codeET = editTexts[1];
        codeET.setEnabled(false);
        custNameET = ViewTool.setFourItemEdit(inflater, root1, new String[]{"自定义产品名称", data.getMaterialName()});
        nameET = ViewTool.setFourItemOnly(inflater, root1, new String[]{"产品标准名称", data.getMaterialCNDesc()})[1];
        nameET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putString("class", CustomDetailFragment.this.getClass().getName());
                FragmentUtil.navigateToInNewActivity(getActivity(), ProSearchListFragment.class, bundle);
            }
        });
        View mView = ViewTool.setFourItem(inflater, root1, new String[]{"产品线", "默认单位"}, new String[]{data.getLevel2(), data.getDefaultUnit()});
        lineNameET = (TextView) mView.findViewById(R.id.text1);
        unitET = (TextView) mView.findViewById(R.id.text2);
        unitET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showUnit();
            }
        });
        LinearLayout root2 = (LinearLayout) rootView.findViewById(R.id.button2);
        ViewTool.createEditItem(inflater, "注册证号", root2, false, true).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putString("id", item.getId());
                bundle.putString("MaterialNumber", data.getMaterialNumber());
                bundle.putString("MaterialName", data.getMaterialName());
                FragmentUtil.navigateToInNewActivity(getActivity(), RegNumberFragment.class, bundle);
            }
        });
        ViewTool.createEditItemNoLine(inflater, "价格列表", root2, false, true).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestPrice(item.getDistCode(), item.getMaterialStCode());
//                Bundle bundle = new Bundle();
//                bundle.putString("id", item.getId());
//                bundle.putString("itemCode", item.getMaterialStCode());
//                bundle.putString("distCode", item.getDistCode());
//                bundle.putString("cusCode", item.getCusCode());
//                FragmentUtil.navigateToInNewActivity(getActivity(), PriceListFragment.class, bundle);
            }
        });
        LinearLayout root3 = (LinearLayout) rootView.findViewById(R.id.button3);
        accountET = ViewTool.setFourItemEdit(inflater, root3, new String[]{"客户名称 （点击选择）", data.getCusName()});
        TextView accountClick = (TextView) ((ViewGroup) accountET.getParent()).findViewById(R.id.title1);
        accountClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putInt("model", 0);
                bundle.putString("class", CustomDetailFragment.this.getClass().getName());
                FragmentUtil.navigateToInNewActivity(getActivity(), AccountChooseFragment.class, bundle);
            }
        });
        LinearLayout root4 = (LinearLayout) rootView.findViewById(R.id.button4);
        editTexts = ViewTool.setFourItemEdit(inflater, root4, new String[]{"产地", "灭菌方式"}, new String[]{data.getOrigin(), data.getSterilization()});
        addressET = editTexts[0];
        typeET = editTexts[1];
        editTexts = ViewTool.setFourItemEdit(inflater, root4, new String[]{"医保编号", "医院物料代码"}, new String[]{data.getMedicalNumber(), data.getHospitalMaterial()});
        numberET = editTexts[0];
        code1ET = editTexts[1];
        unit1ET = ViewTool.setFourItemEdit(inflater, root4, new String[]{"医院物料单位", data.getHospitalMunit()});
        LinearLayout root5 = (LinearLayout) rootView.findViewById(R.id.button5);
        markET = ViewTool.setFourItemEdit(inflater, root5, new String[]{"备注", data.getRemark()});
    }


    private void editPost() {
        if (TextUtils.isEmpty(codeET.getText().toString().trim())) {
            Utils.showToast(getContext(), "标准名称不能为空!");
            return;
        }
        if (TextUtils.isEmpty(custCodeET.getText().toString().trim())) {
            Utils.showToast(getContext(), "自定义产品代码不能为空!");
            return;
        }
        if (TextUtils.isEmpty(custNameET.getText().toString().trim())) {
            Utils.showToast(getContext(), "自定义产品名称不能为空!");
            return;
        }
        if (TextUtils.isEmpty(unitET.getText().toString().trim())) {
            Utils.showToast(getContext(), "默认单位不能为空!");
            return;
        }
        showLoadImg();
        Map<String, String> param = new HashMap<>();
        param.put("id", item.getId());
        param.put("updateType", "0");
        param.put("materialStCode", codeET.getText().toString().trim());
        param.put("materialNumber", custCodeET.getText().toString().trim());
        param.put("materialName", custNameET.getText().toString().trim());
        param.put("materialCNDesc", nameET.getText().toString().trim());
//        param.put("level2", (String) lineNameET.getTag());
//        param.put("subBUCode", (String) lineNameET.getTag());
        param.put("defaultUnit", (String) unitET.getTag());
        param.put("cusName", accountET.getText().toString().trim());
        param.put("origin", addressET.getText().toString().trim());
        param.put("sterilization", typeET.getText().toString().trim());
        param.put("medicalNumber", numberET.getText().toString().trim());
        param.put("hospitalMaterial", code1ET.getText().toString().trim());
        param.put("hospitalMunit", unit1ET.getText().toString().trim());
        param.put("remark", markET.getText().toString().trim());

        getHttpClient().post().url(Constant.UPDATE_DIST_PRODUCT).params(Constant.makeParam(param)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getActivity(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    if (getContext() == null) {
                        return;
                    }
                    dismissLoadImg();
                    Type type = new TypeToken<BaseObjResponse<MockObj>>() {
                    }.getType();
                    BaseObjResponse<MockObj> response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getResult().getCode())) {
                        Utils.showToast(getContext(), "修改成功！");
                        RefershEvent event = new RefershEvent();
                        event.mclass = CustomProFragment.class;
                        EventBus.getDefault().post(event);
                        getActivity().finish();
                    } else {
                        Utils.showToast(getContext(), response.getResult().getMsg());
                    }
                } catch (Exception e) {
                    Utils.showToast(getContext(), "修改失败!");
                }
            }
        });
    }

    private void deletePost() {
        showLoadImg();
        Map<String, String> param = new HashMap<>();
        param.put("id", item.getId());
        param.put("updateType", "1");
        getHttpClient().post().url(Constant.UPDATE_DIST_PRODUCT).params(Constant.makeParam(param)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getActivity(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    if (getContext() == null) {
                        return;
                    }
                    dismissLoadImg();
                    Type type = new TypeToken<BaseObjResponse<MockObj>>() {
                    }.getType();
                    BaseObjResponse<MockObj> response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getResult().getCode())) {
                        Utils.showToast(getContext(), "删除成功！");
                        RefershEvent event = new RefershEvent();
                        event.mclass = CustomProFragment.class;
                        EventBus.getDefault().post(event);
                        getActivity().finish();
                    } else {
                        Utils.showToast(getContext(), response.getResult().getMsg());
                    }
                } catch (Exception e) {
                    Utils.showToast(getContext(), "删除失败!");
                }
            }
        });
    }

    private void showUnit() {
        if (TextUtils.isEmpty(codeET.getText().toString())) {
            Utils.showToast(getContext(), "标准名称不能为空！");
            return;
        }
        if (unitArray == null) {
            requestUnit();
        } else {
            new TwDialogBuilder(getContext()).setItems("选择单位", unitArray, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    unitET.setText(unitArray[i]);
                    unitET.setTag(unitArray[i].split(" ")[0]);
                }
            }).create().show();
        }
    }

    private void requestUnit() {
        showLoadImg();
        Map<String, String> map = new HashMap<>();
        map.put("reqType", "3");
        map.put("itemCode", codeET.getText().toString());
//        map.put("itemCode", "HP054");
        getHttpClient().post().url(Constant.DIC_URL).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                try {
                    JSONObject obj = new JSONObject(s).getJSONObject("result");
                    if ("1".equals(obj.getString("code"))) {
                        JSONArray jsonArray = obj.getJSONArray("uomList");
                        unitArray = new String[jsonArray.length()];
                        for (int j = 0; j < jsonArray.length(); j++) {
                            if (!TextUtils.isEmpty(jsonArray.getJSONObject(j).getString("uomName"))) {
                                unitArray[j] = jsonArray.getJSONObject(j).getString("uom") + " (" + jsonArray.getJSONObject(j).getString("uomName") + ")";
                            } else {
                                unitArray[j] = jsonArray.getJSONObject(j).getString("uom") + " ";
                            }
                        }
                        showUnit();
                    } else {
                        Utils.showToast(getContext(), obj.getString("msg"));
                    }
                } catch (Exception e) {
                    Utils.showToast(getContext(), "解析失败");
                    unitArray = null;
                }
            }
        });
    }

    @Subscribe
    public void onEventMainThread(RefershEvent event) {
        if (event.mclass == getClass()) {
            if (event.oclass == ProSearchListFragment.class) {
                ProductList.ProductItem item = (ProductList.ProductItem) event.bundle.getSerializable("model");
                nameET.setText(item.getItemName());
                codeET.setText(item.getItemCode());
                lineNameET.setText(!TextUtils.isEmpty(item.getSubBUName()) ? item.getSubBUName() : item.getSubBUCode());
                lineNameET.setTag(item.getSubBUCode());
                unitET.setTag(item.getUom());
//                unitET.setText("");
                unitArray = null;
            } else if (event.oclass == AccountChooseFragment.class) {
                String cusCode = event.bundle.getString("code");
                String cusName = event.bundle.getString("name");
                accountET.setText(cusName);
                accountET.setTag(cusCode);
            }
        }
    }

    private void requestPrice(String distCode, String itemCode) {
        showLoadImg();
        Map<String, String> param = new HashMap<>();
//        param.put("distCode", distCode);
        param.put("itemCode", itemCode);
        getHttpClient().post().url(Constant.DIST_PRODUCT_PRICE_LST).params(Constant.makeParam(param)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                Type type = new TypeToken<BaseObjResponse<PriceItem.PriceList>>() {
                }.getType();
                BaseObjResponse<PriceItem.PriceList> response = new Gson().fromJson(s, type);
                if ("1".equals(response.getResult().getCode())) {
                    if(response.getResult().getPriceList().size()==0){
                        Utils.showToast(getContext(),"暂无价格列表");
                    }else{
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model",(ArrayList<PriceItem>)response.getResult().getPriceList());
                        FragmentUtil.navigateToInNewActivity(getActivity(),PriceListFragment.class,bundle);
                    }
//                    adapter.clear();
////                    adapter.addAll(response.getResult().getPriceList());
//                    adapter.addAll(response.getResult().getInvoicePriceList());
//                    adapter.notifyDataSetChanged();
                } else {
                    Utils.showToast(getContext(), response.getResult().getMsg());
                }
            }
        });
    }
}
